﻿using System;
using System.Collections.Generic;
using System.Data;
using TuyennvLibrary.ServerApi.Models;
using TuyennvLibrary.ServerApi.Views;
using Newtonsoft.Json.Linq;
using TuyennvLibrary.Attributes;
using TuyennvLibrary.Enum;
using TuyennvLibrary.Notify;
using TuyennvLibrary.Notify.IOS;
using TuyennvLibrary.Notify.Winphone;
using TuyennvLibrary.Reflection;
using TuyennvLibrary.SqlClient;
using TuyennvLibrary.ServerApi.Controllers;
namespace TuyennvLibrary.ServerApi.ClassApi
{
    [AttributeDescriptionClass(TypeDescriptionClass.Author, "Nguyễn Văn Tuyến")]
    public abstract class BaseApi
    {
        #region Properties
        protected string appid = string.Empty;
        protected ApplicationModel appModel = new ApplicationModel();
        protected DevicesModel devicesModel = new DevicesModel();
        protected ApplicationDevicesModel appDeviceModel = new ApplicationDevicesModel();
        protected ViewApplicationDevicesModel viewAppDeviceModel = new ViewApplicationDevicesModel();
        protected SqlHelper DB = new SqlHelper("SQlConnection", true);
        #endregion
        #region contructor
        public BaseApi(string appid)
        {
            this.appid = appid;
        }
        #endregion

        #region method
        [AttributeDescriptionMethod(TypeDescriptionMethod.Method, "Lấy json config của app")]
        public virtual object getConfig()
        {
            Application app = appModel.GetByID(this.appid);
            JObject json = JObject.Parse(app.config);
            return json;
        }
        [AttributeDescriptionMethod(TypeDescriptionMethod.Method, "Lấy Thông tin của app")]
        public virtual object getApplicationInfo()
        {
            Application app = appModel.GetByID(appid);
            return new { code = Code.SUCCESS, info = app.ToObject(a => new { a.name, a.sender_id }) };
        }
        [AttributeDescriptionMethod(TypeDescriptionMethod.Method, "Lấy các thông tin của device đã đăng ký lên hệ thống")]
        [AttributeDescriptionMethod(TypeDescriptionMethod.Param, "deviceid: id của thiết bị")]
        public virtual object getDeviceInfo(string deviceid)
        {
            Devices d = devicesModel.GetByDeviceid(deviceid);
            return new { code = Code.SUCCESS, info = d };
        }
        [AttributeDescriptionMethod(TypeDescriptionMethod.Method, "Lấy giờ trên hệ thống")]
        [AttributeDescriptionMethod(TypeDescriptionMethod.Param, "format: định dạng giờ cần lấy ví dụ (dd/MM/yyyy)")]
        public object getDateTime(string format)
        {
            string datetime = DateTime.Now.ToString(format);
            return new { code = Code.SUCCESS, datetime };
        }
        [AttributeDescriptionMethod(TypeDescriptionMethod.Method, "Đăng ký thiết bị lên hệ thống")]
        [AttributeDescriptionMethod(TypeDescriptionMethod.Param, "gcmid: registertration đối với android, tokenId đối với IOS, URI đối với Winphone<br />deviceid: id thiết bị<br />platform: 1-Android, 2-IOS, 3-Window phone, 4-J2ME")]
        public virtual object registerDevice(string gcmid, string deviceid, int platform)
        {
            try
            {
                registerDevice(deviceid);
                Devices d = devicesModel.GetByDeviceid(deviceid);
                ApplicationDevices appDevice = appDeviceModel.GetByAppidDeviceid(appid, deviceid);
                d.platform = platform;
                if (d.id <= 0)
                {
                    d.platform = platform;
                    d.deviceid = deviceid;
                    devicesModel.Insert(d);
                }
                
                if (appDevice.id <= 0)
                {
                    appDevice.appid = appid;
                    appDevice.deviceid = deviceid;
                    appDevice.gcmid = gcmid;
                    appDeviceModel.Insert(appDevice);
                }
                else
                {
                    appDevice.gcmid = gcmid;
                    appDeviceModel.Update(appDevice);
                }
                return new { code = Code.SUCCESS, message = "register device success" };
            }
            catch (System.Exception ex)
            {
                return new { code = Code.ERROR, message = ex.Message };
            }
            
        }
        public virtual void registerDevice(string deviceid)
        {
        }
        public NotifyResponse nofityContent(int platform, string Title, object data)
        {
            NotifyResponse response = new NotifyResponse();
            DataTable dtDevice = viewAppDeviceModel.GetListBy(new string[]{
                ViewApplicationDevices.COLUMN_APPID,
                ViewApplicationDevices.COLUMN_PLATFORM
            }, new object[]{
                this.appid,
                platform
            }, ViewApplicationDevices.COLUMN_ID + " desc");
            List<object> listRegistrations = MessageController.getregistration_ids(dtDevice);
            if (platform == 1)
            {
                response = MessageController.sendMessageAndroidForMultiDevice(this.appid, listRegistrations, data);
            }
            else if (platform == 2)
            {
                Application app = appModel.GetByID(appid);
                List<List<NotificationPayload>> listPageNotification = MessageController.getPagesPushIOS(dtDevice, Title, data);
                response = MessageController.sendMessageIOSForMultiDevice(listPageNotification, Config.Server.MapPath(app.filep12), app.passp12, IOSNotify.PRODUCTION_HOST);
            }

            return response;
        }
        public NotifyResponse notifyWinphone(WinphoneNotify notify)
        {
            NotifyResponse response = new NotifyResponse();
            DataTable dt = viewAppDeviceModel.GetListBy(new string[] { ViewApplicationDevices.COLUMN_APPID, ViewApplicationDevices.COLUMN_PLATFORM }, new object[] { appid, 3 }, ViewApplicationDevices.COLUMN_ID + " desc");
            List<string> listResponse = new List<string>();
            foreach (DataRow dr in dt.Rows)
            {
                string uri = dr.GetString(ApplicationDevices.COLUMN_GCMID, "");
                if (!string.IsNullOrEmpty(uri))
                {
                    try
                    {
                        notify.Uri = uri;
                        NotifyResponse responseTemp = notify.Push();
                        response.Add(responseTemp);
                    }
                    catch (Exception)
                    {

                    }
                }
            }
            return response;
        }
        #endregion
    }
}
